package com.glela.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.glela.cache.redis.RedisUtil;
import com.glela.common.util.DateUtil;
import com.glela.goods.model.DistributaryTemplate;
import com.glela.goods.model.DistributaryTemplateDetails;
import com.glela.goods.service.DistributaryService;
import com.glela.platform.constant.ErrorEnum;
import com.glela.platform.model.request.RequestUserModel;
import com.glela.platform.model.response.ResponseBaseModel;
import com.glela.platform.model.response.ResponseResultModel;
import com.glela.platform.service.BaseRestrictionsService;

/**
* @ClassName: PreloadController 
* @Description: 预加载类控制器
* @author NingChongQing
* @date 2017年10月13日 下午3:35:14
 */
@Controller
@RequestMapping(value = "/preload")
public class PreloadController extends BaseController {
	private static Logger logger = LoggerFactory.getLogger(PreloadController.class);
	@Autowired
	private BaseRestrictionsService baseRestrictionsService;
	@Autowired
	private DistributaryService distributaryService;
	@Autowired
	private RedisUtil redisUtil;
	
	/**
	 * 
	* **********************************************
	* @Title: loadActivityInfo 
	* @Description: 加载活动信息【双11活动等···】
	* @param @param model
	* @param @return 
	* @return ResponseEntity<?>
	* @throws	
	* @author NingChongQing	
	* @date 2017年10月13日 下午3:35:07 
	* **********************************************
	 */
	@RequestMapping(value = "/loadActivityInfo", method = RequestMethod.POST, consumes = "application/json")
	public ResponseEntity<?> loadActivityInfo(@RequestBody RequestUserModel model, HttpServletRequest request)
	{
		try {
			// 活动类型
			String activityType = "11.08";
			try {
				activityType = this.baseRestrictionsService.getBaseRestrictionsForCache("activity_type").getName();
			} catch (Exception e) {
				
			}
			// 活动开始时间
			long activityBeginTime = 0;
			try {
				activityBeginTime = DateUtil.parse(this.baseRestrictionsService.getBaseRestrictionsForCache("activity_begin_time").getName()).getTime();
			} catch (Exception e) {
				
			}
			// 活动结束时间
			long activityEndTime = 0;
			try {
				activityEndTime = DateUtil.parse(this.baseRestrictionsService.getBaseRestrictionsForCache("activity_end_time").getName()).getTime();
			} catch (Exception e) {
				
			}
			// 拦截开始时间
			long interceptBeginTime = 0;
			try {
				interceptBeginTime = DateUtil.parse(this.baseRestrictionsService.getBaseRestrictionsForCache("intercept_begin_time").getName()).getTime();
			} catch (Exception e) {
				
			}
			// 拦截结束时间
			long interceptEndTime = 0;
			try {
				interceptEndTime = DateUtil.parse(this.baseRestrictionsService.getBaseRestrictionsForCache("intercept_end_time").getName()).getTime();
			} catch (Exception e) {
				
			}
			// 拦截URL列表
			String[] interceptArray  =  null;
			try {
				interceptArray  =  this.baseRestrictionsService.getBaseRestrictionsForCache("intercept_urls").getName().split(";");
			} catch (Exception e) {
				
			}
			// 服务器当前时间
			long serverCurrentTime = System.currentTimeMillis();
			// 活动标识：0未开始；1活动中；2已结束
			int underway = 0;// 默认：活动未开始
			if(serverCurrentTime > activityEndTime) {// 活动已结束
				underway = 2;
			} else if(serverCurrentTime > activityBeginTime){// 活动中
				underway = 1;
			}
			// 是否拦截 0：未开始，1：拦截，2：拦截结束
			Integer isIntercept = 0;
			if (serverCurrentTime > interceptEndTime) {// 拦截结束
				isIntercept = 2;
			} else if (serverCurrentTime > interceptBeginTime) {// 拦截中
				isIntercept = 1;
			}
			// 拦截与否都要返回拦截的列表，因为前段会计算拦截开始于结束
			List<Map<String, Object>> interceptUrlList = new ArrayList<Map<String, Object>>();
			if (interceptArray != null && interceptArray.length > 0) {
				for (int i=0;i<interceptArray.length;i++) {
					Map<String, Object> map = new HashMap<String, Object>();
					map.put("url",interceptArray[i].split("\\|")[0]);
					map.put("isPopover",Integer.valueOf(interceptArray[i].split("\\|")[1]));
					interceptUrlList.add(map);
				}
			}
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("activityType",activityType);
			map.put("activityBeginTime",activityBeginTime);
			map.put("activityEndTime", activityEndTime);
			map.put("underway", underway);
			map.put("serverCurrentTime",serverCurrentTime);
			map.put("isIntercept", isIntercept);
			map.put("interceptUrlList", interceptUrlList);
			map.put("interceptBeginTime", interceptBeginTime);
			map.put("interceptEndTime", interceptEndTime);
			map.put("distributaryEntrance", this.distributaryEntrance());// 分流入口
			return new ResponseEntity<>(new ResponseResultModel<>(map), HttpStatus.OK);
		} catch (Exception e) {
			logger.error("预加载异常", e);
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
		}
	}
	
	/**
	* *
	* @Title: distributaryEntrance 
	* @Description: 分流入口
	* @param @return 
	* @return List<DistributaryTemplateDetailsResponse>
	* @throws	
	* @author NingChongQing	
	* @date 2018年3月20日 上午11:42:01 
	* **********************************************
	 */
	public Map<String, Object> distributaryEntrance() {
		Map<String, Object> result = new HashMap<String, Object>();
		try {
			String tempKey = "temp:distributary_entrance";
			String rslt = redisUtil.get(tempKey);
			int showFlag = 0;// 是否显示分流入口菜单
			if (StringUtils.isEmpty(rslt)) {
				List<DistributaryTemplate> dtList = this.distributaryService.achieveAvailableTemplate();
				if (!CollectionUtils.isEmpty(dtList)) {
					List<DistributaryTemplateDetails> dtdList = this.distributaryService.achieveAvailableTemplateDetails(dtList.get(0).getId());
					if (!CollectionUtils.isEmpty(dtdList)) {
						showFlag = 1;
						// 普通专题H5地址
						String h5_activity_url = this.baseRestrictionsService.getBaseRestrictionsForCache("h5_activity_url").getName();
						List<JSONObject> details = new ArrayList<JSONObject>();
						for (DistributaryTemplateDetails dtd : dtdList) {
							JSONObject jsonObj = new JSONObject();
							jsonObj.put("title", dtd.getTitle());
							jsonObj.put("iconUrl", dtd.getIconUrl());
							jsonObj.put("type", dtd.getType());
							String jumpValue = dtd.getJumpValue();
							String jumpUrl = dtd.getJumpValue();
							if (dtd.getType() == 1) {// 普通专题页跳转
								jumpUrl = h5_activity_url + "id=" + jumpUrl;
							} else {// 特殊专题
								jumpValue = "0";
							}
							jsonObj.put("jumpValue", jumpValue);
							jsonObj.put("jumpUrl", jumpUrl);
							jsonObj.put("sortNumber", dtd.getSortNumber());
							details.add(jsonObj);
						}
						result.put("showFlag", showFlag);
						result.put("templateNo", dtList.get(0).getTemplateNo());
						result.put("details", details);
						// 缓存生效时间30分钟
						redisUtil.set(tempKey, JSON.toJSONString(result), 1800);
					}
				}
			} else {
				result = JSON.parseObject(rslt);
			}
		} catch (Exception e) {
			logger.error("获取可用模板信息异常", e);
		}
		return result;
	}
}
